package com.kerbores.kop.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.adapters.HexBinaryAdapter;

public class SignUtil {

	public static String getSign(Map<String, Object> params, boolean fileUpload, String appKey, String appSecret) {
		if (fileUpload) {
			String target = null;
			try {
				target = new HexBinaryAdapter().marshal(MessageDigest.getInstance("SHA-1").digest((appKey + appSecret).getBytes("UTF-8")));
			} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return target;
		}
		List<String> datas = new ArrayList<String>();
		for (Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
			String key = it.next();
			String data = key + "=" + params.get(key);
			datas.add(data);
		}
		Collections.sort(datas);// 排序
		String target = appKey;
		for (String data : datas) {
			target += data;
		}
		try {
			target = new HexBinaryAdapter().marshal(MessageDigest.getInstance("SHA-1").digest((target + appSecret).getBytes("UTF-8")));
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return target;
	}
}
